<template>
  <v-form v-model="form.valid">
    <v-container v-if="paySuccess == 'notsuccess'" class="contain">
      <v-row class="mt-10" justify="center">
        <v-col cols="8">
          <v-alert outlined prominent type="fail">
            {{ $t('payfailed') }}
          </v-alert>
        </v-col>
      </v-row>
      <v-row justify="center">
        <v-btn
          id="pay"
          class="mr-2"
          type="button"
          dark
          @click="$router.push(localePath('/orderlist'))"
          >{{ $t('goordercenter') }}
        </v-btn>
        <v-btn id="pay" class="mr-2" type="button" dark @click="paySuccess = false"
          >{{ $t('repay') }}
        </v-btn>
      </v-row>
    </v-container>
    <v-container v-else-if="paySuccess" class="contain">
      <v-row class="mt-10" justify="center">
        <v-col cols="8">
          <v-alert outlined prominent type="success">
            {{ $t('payok') }}
          </v-alert>
        </v-col>
      </v-row>
      <v-row justify="center">
        <v-btn id="pay" class="mr-2" type="button" dark @click="$router.push(localePath('/'))">{{
          $t('backhome')
        }}</v-btn>
        <v-btn
          id="pay"
          class="mr-2"
          type="button"
          dark
          @click="
            $router.push(
              localePath({ path: '/orderdetail', query: { ordersn: $route.query.ordersn } })
            )
          "
          >{{ $t('checkorder') }}
        </v-btn>
      </v-row>
    </v-container>
    <v-container v-show="!paySuccess" class="contain mb-4">
      <v-row class="mt-10 px-4" justify="center">
        <v-col cols="12" sm="6">
          <div id="card" />
        </v-col>
      </v-row>
      <v-row justify="center" align="center">
        <v-col cols="6"
          >{{ $t('coin')
          }}<v-text-field
            v-model="detail.deposit_fee"
            style="margin-left: 8px; display: inline-block; width: 80%"
            outlined
            type="number"
        /></v-col>
      </v-row>
      <v-row justify="center" class="mb-4">
        <v-btn id="pay" type="button" dark>Pay </v-btn>
      </v-row>
      <v-row justify="center" class="mb-4">
        <div class="w-50">
          <h2 class="mt-4">{{ $t('orderdetail') }}</h2>
          <v-row align="center" class="mt-10">
            <v-col cols="12" sm="6">
              <v-text-field v-model="detail.ordersn" :label="$t('orderno')" disabled />
            </v-col>

            <v-col cols="12" sm="6">
              <v-img :src="detail.brand.brand_logo" width="100" disabled />
            </v-col>

            <v-col cols="12" sm="6">
              <v-text-field
                :value="detail.carmodelshow.model_num"
                :label="$t('modelnum')"
                disabled
              />
            </v-col>

            <v-col cols="12" sm="6">
              <v-text-field :value="detail.goods.car_no" :label="$t('carno')" disabled />
            </v-col>

            <v-col cols="12" sm="6">
              <v-text-field :value="detail.goods.name" :label="$t('name')" disabled />
            </v-col>

            <v-col cols="12" sm="6">
              <v-text-field :value="detail.starttime_text" :label="$t('begintime')" disabled />
            </v-col>

            <v-col cols="12" sm="6">
              <v-text-field :value="detail.endtime_text" :label="$t('endtime')" disabled />
            </v-col>

            <v-col cols="12" sm="6">
              <v-text-field
                :value="detail.createtime_text"
                :label="$t('createordertime')"
                disabled
              />
            </v-col>
          </v-row>
        </div>
      </v-row>
    </v-container>
    <v-overlay :value="loading">
      <v-progress-circular indeterminate size="64" />
    </v-overlay>
  </v-form>
</template>

<script>
import { v4 as uuidv4 } from 'uuid';

export default {
  name: 'PayBond',
  data: () => ({
    form: {
      valid: false
    },
    detail: {
      brand: {},
      carmodelshow: {},
      goods: {}
    },
    paySuccess: false,
    loading: false
  }),
  mounted() {
    this.start();
    this.getInfo();
  },
  methods: {
    async start() {
      const applicationId = 'sq0idp-ALbXpw_AGD-rWQc3blNSGw';
      const locationId = 'LES6Q1EK6SQZC';
      // const applicationId = 'sandbox-sq0idb-wzwIsq18MJfbJBz-l8o1kQ';
      // const locationId = 'LYN26CSWASGG6';
      const Square = await import('@square/web-sdk');
      const payments = await Square.payments(applicationId, locationId);
      const card = await payments.card();

      await card.attach('#card');

      document.querySelector('#pay').addEventListener('click', async () => {
        this.loading = true;
        try {
          const tokenResult = await card.tokenize();
          if (!tokenResult.token) {
            return;
          }
          const res = await this.$api.fetch(
            '/order/createDepositPayment',
            // {
            //   "ordersn": "2024111457102485",//订单号
            //   "sourceId": "cnon:CBASEIjuuI1pf750NkK97CGiocgoAg",//sourceId  前端验卡后获取到数据
            //   "idempotencyKey": "82a66d07-db08-4cbc-a237-14fdbd0b2ad5"//idempotencyKey 前端验卡后获取到数据
            // }

            {
              ordersn: this.$route.query.ordersn, // 订单号
              sourceId: tokenResult.token, // sourceId  前端验卡后获取到数据
              idempotencyKey: window.crypto.randomUUID ? window.crypto.randomUUID() : uuidv4(), // idempotencyKey 前端验卡后获取到数据
              deposit_fee: this.detail.deposit_fee
              // "idempotencyKey": window.crypto.randomUUID()//idempotencyKey 前端验卡后获取到数据
            },
            { getAll: true, timeout: 60000 }
          );
          this.loading = false;
          if (res.code === 1) {
            console.log(res);
            const response = await this.$api.post(
              '/order/checkDepositPayStatus',
              {
                ordersn: this.$route.query.ordersn // 订单号
              },
              { getAll: true }
            );
            if (response.data && response.data.deposit_status === 1) {
              // todo//支付状态 0未支付 1支付中 2支付成功 3支付失败 11退款中 12退款成功
              this.paySuccess = true;
              console.log(response.data);
            } else {
              this.paySuccess = 'notsuccess';
            }
          }
        } catch (ex) {
          console.error(ex);
        }
      });
    },
    getInfo() {
      this.$api
        .post('/order/getOrderInfo', { ordersn: this.$route.query.ordersn }, { getAll: true })
        .then((res) => {
          console.log(res.data);
          this.detail = res.data;
        });
    }
  }
};
</script>
<style>
.w-50 {
  width: 50vw;
}
@media screen and (max-width: 600px) {
  .w-50 {
    width: 90vw !important;
  }
}
</style>
